#define PORT 6666
#include <iostream>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <netinet/in.h>
#include <time.h>

using namespace std;

int main()
{
	time_t t=time(0);
    char buffer[1024];
    char msg[1024];
    int sock_fd,client_fd;
    socklen_t sin_size;
    int rtv=0;
    struct sockaddr_in my_addr;
    struct sockaddr_in remote_addr;
    rtv=sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if( rtv == -1)
    {
        cout<<"socket create error."<<endl;
        return 1;
    }
    else
    {
	cout<<"socket create success!"<<endl;
    }
    my_addr.sin_family=AF_INET;
    my_addr.sin_port=htons(PORT);
    my_addr.sin_addr.s_addr = INADDR_ANY;
	rtv=bind(sock_fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
    if(rtv == -1) {
        cout<<"bind error."<<endl;
        return 1;
    }
    else
	{
		cout<<"bind success!"<<endl;
	}
	rtv=listen(sock_fd, 10);

    if(rtv == -1) {
        cout<<"send failed."<<endl;
        return 1;
    }
	else
	{
		cout<<"listen success!"<<endl;
	}
    while(1)
	{
	cout<<"start listening..."<<endl;
        sin_size = sizeof(struct sockaddr_in);
	rtv=client_fd = accept(sock_fd, (struct sockaddr *)&remote_addr, &sin_size);
        if( rtv == -1) {
            cout<<"accept error!"<<endl;
            continue;
        }
	cout<<"get Connection!"<<endl;
        if(!fork()) {
			while(strcmp(buffer,"quit"))
			{
            	rtv=recv(client_fd, &buffer, 1024, 0);
       			if( rtv == -1) {
       	  	      	cout<<"recv failed."<<endl;
        	    }
				if(!strcmp(buffer,"quit"))
					break;
         	   
				strftime(msg,sizeof(msg),buffer,localtime(&t));
        	    rtv=send(client_fd, &msg, 1024, 0);
         	   if( rtv == -1) {
      	          cout<<"send failed."<<endl;
       	    	 }
			}
            close(client_fd);
            return 0;
        }
        close(client_fd);
    }
}

